import cgi
import os
import string
import time
import logging
import wsgiref.handlers
from google.appengine.ext.webapp import template
from google.appengine.ext import webapp
from google.appengine.ext import db

from AEProxy import  ApiConfig

appkey = None
secret = None
url = None
v = None

class SetupController(webapp.RequestHandler):
	def get(self):
		html = self.do_init()
		self.response.out.write(html)

	def do_init(self):
		req = self.request
		appkey = req.get('appkey')
		secret = req.get('secret')
		url = req.get('url')
		v= req.get('v')
		msg = ""
		if((appkey == '') | (secret == '')):
			msg = "error params"
			return msg

		if(ApiConfig.all().count() > 0):
			msg = "already init"
		else:
			config = ApiConfig()
			config.appkey = appkey
			config.secret = secret
			config.url = url
			config.v = v
			config.put()
			msg = "success"

		if((appkey is None) | (secret is None)):
			store = ApiConfig.all()[0]
			appkey = store.appkey
			secret = store.secret
			url = store.url
			v = store.v
		return msg

def main():
	application = webapp.WSGIApplication(
                                       [('/setup', SetupController)])
	wsgiref.handlers.CGIHandler().run(application)

if __name__ == "__main__":
	main()